package com.example.myproject.controller;

import com.example.myproject.dto.*;
import com.example.myproject.dto.login.ChangePasswordRequest;
import com.example.myproject.dto.login.LoginRequest;
import com.example.myproject.dto.login.RegisterRequest;
import com.example.myproject.dto.login.VerifyEmailRequest;
import com.example.myproject.security.JwtAuthenticationFilter;
import com.example.myproject.service.PermissionService;
import com.example.myproject.service.UserService;
import com.example.myproject.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("/api/user")
public class UserController {

    @Autowired private UserService userService;
    @Autowired private PermissionService permissionService;

    @PostMapping("/register")//测试成功
    public ApiResponse<RegisterResponse> register(@RequestBody RegisterRequest req) {
        Long id = userService.register(req);
        return ApiResponse.success(200, "注册成功，请查收验证邮件",
                new RegisterResponse(id));
    }

    /**
     * 浏览器点链接时用 GET
     * 例如：http://localhost:8080/api/user/verify?email=xxx&token=yyy
     */
    @GetMapping("/verify")//测试成功
    public ApiResponse<TokenResponse> verifyGet(
            @RequestParam("email") String email,
            @RequestParam("token") String token) {
        // 手动构造 DTO
        VerifyEmailRequest req = new VerifyEmailRequest();
        req.setEmail(email);
        req.setToken(token);
        String access = userService.verifyEmail(req);
        return ApiResponse.success(200, "邮箱验证成功", new TokenResponse(access));
    }

    /**
     * 保留原来的 POST 验证接口，
     * 如果你调用 REST 客户端或前端 ajax，也可以走 POST+JSON
     */
    @PostMapping("/verify")
    public ApiResponse<TokenResponse> verify(@RequestBody VerifyEmailRequest req) {
        String access = userService.verifyEmail(req);
        return ApiResponse.success(200, "邮箱验证成功", new TokenResponse(access));
    }


    @PostMapping("/login")//测试成功。已解决username的问题
    public ApiResponse<LoginResponse> login(@RequestBody LoginRequest req) {
        LoginResponse resp = userService.login(req);
        System.out.println(req);
        return ApiResponse.success(200, "登录成功", resp);
    }

    @GetMapping("/info")
    public ApiResponse<com.example.myproject.dto.user.UserInfoDTO> getUserInfo() {
        // 从当前登录用户获取用户ID
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        Long userId = ((JwtAuthenticationFilter.UserPrincipal) auth.getPrincipal()).getId();

        com.example.myproject.dto.user.UserInfoDTO userInfo = userService.getUserInfo1(userId);
        return ApiResponse.success(200, "获取成功", userInfo);
    }
//    @GetMapping("/info")//测试成功
//    public ApiResponse<UserInfoVO> getInfo(
//            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal) {
//        Long userId = principal.getId();
//        UserInfoVO vo = userService.getUserInfo(userId);
//        return ApiResponse.success(200, "success", vo);
//    }

    @PutMapping("/info")//测试成功
    public ApiResponse<Void> updateInfo(
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal,
            @RequestBody UpdateUserInfoRequest req) {
        userService.updateUserInfo(principal.getId(), req);
        return ApiResponse.success(200, "用户信息更新成功");
    }


    @GetMapping("/info/{userId}")
    public ApiResponse<com.example.myproject.dto.user.UserInfoDTO> getUserInfoById(@PathVariable Long userId) {
        com.example.myproject.dto.user.UserInfoDTO userInfo = userService.getUserInfo1(userId);
        return ApiResponse.success(200, "获取成功", userInfo);
    }

    @PutMapping("/password")//测试成功
    public ApiResponse<Void> changePassword(
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal,
            @RequestBody ChangePasswordRequest req) {
        userService.changePassword(principal.getId(), req);
        return ApiResponse.success(200, "密码修改成功");
    }

    @GetMapping("/permissions")//测试失败，permission表未建完
    public ApiResponse<PermissionVO> getPermissions(
            @AuthenticationPrincipal JwtAuthenticationFilter.UserPrincipal principal) {
        // 从 principal 获取正确的 userId
            PermissionVO vo = permissionService.getPermissions(principal.getId());
            return ApiResponse.success(200, "success", vo);
    }
}